import { Outlet, useNavigate, useLocation } from "react-router-dom";
import { Layout, Menu, Typography } from "antd";
import { HomeOutlined, UserOutlined } from "@ant-design/icons";
import { useSelector } from "react-redux";
import type { RootState } from "./store/store";

const { Header, Footer, Sider, Content } = Layout;
const { Text } = Typography;

export default function App() {
  const navigate = useNavigate();
  const location = useLocation();

  // 从 Redux 获取 username
  const username = useSelector((state: RootState) => state.auth.username);

  const menuItems = [
    {
      key: "1",
      icon: <HomeOutlined />,
      label: "展示父子组件通信",
      onClick: () => navigate("/app/home"),
    },
    {
      key: "2",
      icon: <UserOutlined />,
      label: "列表与样式隔离",
      onClick: () => navigate("/app/about"),
    },
    {
      key: "3",
      icon: <UserOutlined />,
      label: "Portal使用",
      onClick: () => navigate("/app/portal"),
    },
    {
      key: "4",
      icon: <UserOutlined />,
      label: "Context使用",
      onClick: () => navigate("/app/context"),
    },
  ];

  const selectedKeys = [
    location.pathname === "/app/home"
      ? "1"
      : location.pathname === "/app/about"
      ? "2"
      : "",
  ];

  const headerStyle: React.CSSProperties = {
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    color: "#fff",
    height: 64,
    paddingInline: 48,
    backgroundColor: "#4096ff",
  };

  const contentStyle: React.CSSProperties = {
    padding: 24,
    minHeight: "calc(100vh - 64px - 69px)", // 减去 header 和 footer 高度
    color: "#000",
    backgroundColor: "#fff",
  };

  const siderStyle: React.CSSProperties = {
    color: "#fff",
    backgroundColor: "#1677ff",
  };

  const footerStyle: React.CSSProperties = {
    textAlign: "center",
    color: "#fff",
    backgroundColor: "#4096ff",
  };

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Header style={headerStyle} onClick={() => navigate("/login")}>
        <Text strong style={{ color: "#fff", fontSize: 18 }}>
          系统名称
        </Text>
        {username && <Text style={{ color: "#fff" }}>欢迎，{username}！</Text>}
      </Header>
      <Layout>
        <Sider width={200} style={siderStyle}>
          <Menu
            theme="dark"
            mode="vertical"
            items={menuItems}
            selectedKeys={selectedKeys}
            style={{ height: "100%" }}
          />
        </Sider>
        <Content style={contentStyle}>
          <Outlet />
        </Content>
      </Layout>
      <Footer style={footerStyle}>©2024 公司名称</Footer>
    </Layout>
  );
}
